<template>
  <view class="bind-card-container">
    <view class="card-list-section">
      <view class="section-title">已绑定银行卡</view>
      <view v-if="cardList.length === 0" class="wx-empty-tip">
        <image src="/static/images/empty-card.png" class="wx-empty-img" mode="aspectFit" />
        <view class="wx-empty-text">暂无已绑定银行卡</view>
      </view>
      <view v-for="card in cardList" :key="card.id" class="wx-card-item">
        <view class="wx-card-row">
          <view class="wx-card-no">{{ maskCardNo(card.chCardNo) }}</view>
          <view class="wx-card-actions">
            <button class="wx-unbind-btn" @click="showUnbindConfirm(card)">解绑</button>
            <uni-icons type="right" size="22" color="#bbb" />
          </view>
        </view>
        <view class="wx-card-info-row">
          <text class="wx-card-bank">{{ card.bankName || '储蓄卡' }}</text>
          <text class="wx-card-owner">{{ maskName(card.chName) }}</text>
          <text class="wx-card-owner">{{ maskPhone(card.chMobile) }}</text>
        </view>
      </view>
    </view>
    <view class="bind-btn-section">
      <button type="primary" @click="openBindPopup">去绑定银行卡</button>
    </view>
    <uni-popup ref="bindPopup" type="center">
      <view class="wx-bind-popup-bg">
        <view class="wx-bind-popup">
          <view class="wx-popup-title">绑定银行卡</view>
          <view class="wx-form-list">
            <view class="wx-form-item">
              <text class="wx-label">银行卡号<text class="wx-required">*</text></text>
              <input class="wx-input" v-model="form.cardNo" placeholder="请输入银行卡号" />
            </view>
            <view class="wx-form-item">
              <text class="wx-label">持卡人姓名<text class="wx-required">*</text></text>
              <input class="wx-input" v-model="form.name" placeholder="请输入姓名" />
            </view>
            <view class="wx-form-item">
              <text class="wx-label">证件号<text class="wx-required">*</text></text>
              <input class="wx-input" v-model="form.idNo" placeholder="请输入身份证号" />
            </view>
            <view class="wx-form-item">
              <text class="wx-label">手机号<text class="wx-required">*</text></text>
              <input class="wx-input" v-model="form.phone" placeholder="请输入银行预留手机号" />
            </view>
            <view class="wx-form-item">
              <text class="wx-label">卡类型<text class="wx-required">*</text></text>
              <picker :range="cardTypeOptions" v-model="form.cardTypeIdx">
                <view class="picker-value">{{ cardTypeOptions[form.cardTypeIdx] }}</view>
              </picker>
            </view>
            <!-- <view class="wx-form-item">
              <text class="wx-label">安全码</text>
              <input class="wx-input" v-model="form.cvv2" placeholder="信用卡填安全码，借记卡可不填" />
            </view> -->
            <view class="wx-form-item">
              <text class="wx-label">有效期</text>
              <picker :range="validDateOptions" :value="form.validDateIdx" @change="onValidDateChange">
                <view class="picker-value">{{ validDateOptions[form.validDateIdx] || '请选择有效期' }}</view>
              </picker>
            </view>
          </view>
          <view v-if="showSms" class="wx-sms-section">
            <view class="wx-qrcode-label">请输入6位短信验证码</view>
            <view class="wx-sms-code-box" style="position:relative;">
              <input
                class="wx-sms-code-input"
                v-model="smsCodeInput"
                maxlength="6"
                type="number"
                @input="onSmsInput"
                ref="smsInput"
                style="opacity:0;position:absolute;top:0;left:0;width:100%;height:100%;z-index:1;"
              />
              <view class="wx-sms-code-cells">
                <view v-for="i in 6" :key="i" class="wx-sms-code-cell" :class="{active: smsCodeInput.length === i-1}">
                  {{ smsCodeInput[i-1] ? smsCodeInput[i-1] : '' }}
                </view>
              </view>
            </view>
            <button type="primary" :loading="confirmLoading" class="wx-btn" @click="onConfirmSign">确定绑卡</button>
          </view>
          <view v-else class="wx-btn-section">
            <button type="primary" :loading="readyLoading" class="wx-btn" @click="onReadySign">预定绑卡</button>
            <button class="wx-btn-cancel" @click="closeBindPopup">取消</button>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getCardList, readySign, confirmSign, addCard, unSignCard } from '@/api/login'
export default {
  data() {
    return {
      cardList: [],
      showBindForm: false,
      form: {
        cardNo: '',
        name: '',
        idNo: '',
        phone: '',
        cvv2: '',
        validDateIdx: null,
        cardTypeIdx: 0,
        userId: ''
      },
      cardTypeOptions: ['借记卡', '信用卡'],
      validDateOptions: [
        '01/25', '02/25', '03/25', '04/25', '05/25', '06/25', '07/25', '08/25', '09/25', '10/25', '11/25', '12/25',
        '01/26', '02/26', '03/26', '04/26', '05/26', '06/26', '07/26', '08/26', '09/26', '10/26', '11/26', '12/26',
        '01/27', '02/27', '03/27', '04/27', '05/27', '06/27', '07/27', '08/27', '09/27', '10/27', '11/27', '12/27',
        '01/28', '02/28', '03/28', '04/28', '05/28', '06/28', '07/28', '08/28', '09/28', '10/28', '11/28', '12/28',
        '01/29', '02/29', '03/29', '04/29', '05/29', '06/29', '07/29', '08/29', '09/29', '10/29', '11/29', '12/29',
        '01/30', '02/30', '03/30', '04/30', '05/30', '06/30', '07/30', '08/30', '09/30', '10/30', '11/30', '12/30',
        '01/31', '02/31', '03/31', '04/31', '05/31', '06/31', '07/31', '08/31', '09/31', '10/31', '11/31', '12/31',
        '01/32', '02/32', '03/32', '04/32', '05/32', '06/32', '07/32', '08/32', '09/32', '10/32', '11/32', '12/32',
        '01/33', '02/33', '03/33', '04/33', '05/33', '06/33', '07/33', '08/33', '09/33', '10/33', '11/33', '12/33',
        '01/34', '02/34', '03/34', '04/34', '05/34', '06/34', '07/34', '08/34', '09/34', '10/34', '11/34', '12/34',
      ],
      readyLoading: false,
      confirmLoading: false,
      showSms: false,
      smsCodeInput: '',
      unique_code:''
    }
  },
  methods: {
    async getCardList() {
      try {
        const res = await getCardList()
        if (res.code === 200 && res.data) {
          this.cardList = res.data
        } else {
          this.cardList = []
        }
      } catch (e) {
        this.cardList = [
          {
            cardNo: '6222021001015343573',
            cardName: '中国工商银行 储蓄卡',
            owner: '王勇'
          },
          {
            cardNo: '6227002871234567890',
            cardName: '中国建设银行 储蓄卡',
            owner: '李明'
          }
        ]
      }
    },
    async onReadySign() {
      if (!this.form.cardNo || !this.form.name || !this.form.idNo || !this.form.phone) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' })
        return
      }
      this.readyLoading = true
      const cardInfo = [
        this.form.cardNo || '',
        this.form.name || '',
        this.form.idNo || '',
        this.form.phone || '',
        this.form.cvv2 || '',
        (this.form.validDateIdx !== null && this.form.validDateIdx !== undefined) ? this.validDateOptions[this.form.validDateIdx] : ''
      ].join('|')
      const cardType = this.form.cardTypeIdx === 0 ? '101' : '102'
      try {
        const res = await readySign({ cardInfo, cardType, userId: this.form.userId })
        if (res.code === 200 && res.data && res.data.biz_resp_code === '0000') {
          this.showSms = true
          this.unique_code = res.data.unique_code2
          console.log(res.data.unique_code2)
          uni.showToast({ title: '请输入短信验证码', icon: 'none' })
          this.$nextTick(() => {
            this.focusSmsInput();
          })
        } else {
          uni.showToast({ title: res.data?.biz_resp_msg || res.msg || '预定绑卡失败', icon: 'none' })
        }
      } catch (e) {
        uni.showToast({ title: '预定绑卡失败', icon: 'none' })
      } finally {
        this.readyLoading = false
      }
    },
    async onConfirmSign() {
      if (this.smsCodeInput.length !== 6) {
        uni.showToast({ title: '请填写完整短信验证码', icon: 'none' })
        return
      }
      this.confirmLoading = true
      try {
        const res = await confirmSign(this.unique_code, this.smsCodeInput)
        if (res.code === 200 && res.data && res.data.biz_resp_code === '0000') {
          const addRes = await addCard({
            chCardNo: this.form.cardNo,
            chIdNo: this.form.idNo,
            chMobile: this.form.phone,
            chName: this.form.name,
            protocolNo: res.data.protocol_no2
          })
          if (addRes.code === 200) {
            uni.showToast({ title: '绑卡成功', icon: 'success' })
            // 关闭弹窗
            this.closeBindPopup()
            // 重置表单数据
            this.form = {
              cardNo: '',
              name: '',
              idNo: '',
              phone: '',
              cvv2: '',
              validDateIdx: null,
              cardTypeIdx: 0,
              userId: this.form.userId
            }
            // 重置SMS相关状态
            this.showSms = false
            this.smsCodeInput = ''
            this.unique_code = ''
            // 刷新卡列表
            this.getCardList()
          } else {
            uni.showToast({ title: addRes.msg || '绑卡添加失败', icon: 'none' })
          }
        } else {
          uni.showToast({ title: res.data?.biz_resp_msg || res.msg || '绑卡失败', icon: 'none' })
        }
      } catch (e) {
        uni.showToast({ title: '绑卡失败', icon: 'none' })
      } finally {
        this.confirmLoading = false
      }
    },
    openBindPopup() {
      this.showBindForm = true;
      this.$nextTick(() => {
        this.$refs.bindPopup.open && this.$refs.bindPopup.open();
      });
    },
    closeBindPopup() {
      this.showBindForm = false;
      this.$refs.bindPopup.close && this.$refs.bindPopup.close();
    },
    maskCardNo(cardNo) {
      if (!cardNo) return '';
      return cardNo.replace(/(\d{4})\d+(\d{4})/, '$1 **** **** $2');
    },
    maskName(name) {
      if (!name) return '';
      if (name.length === 2) return name[0] + '*';
      if (name.length > 2) return name[0] + '*'.repeat(name.length - 2) + name[name.length - 1];
      return name;
    },
    maskPhone(phone) {
      if (!phone) return '';
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },
    onValidDateChange(e) {
      this.form.validDateIdx = e.detail.value;
    },
    focusSmsInput() {
      this.$refs.smsInput && this.$refs.smsInput.focus && this.$refs.smsInput.focus();
    },
    onSmsInput(e) {
      this.smsCodeInput = (e.detail.value || '').replace(/\D/g, '').slice(0, 6);
    },
    showUnbindConfirm(card) {
      uni.showModal({
        title: '提示',
        content: `确定要解绑银行卡 ${this.maskCardNo(card.chCardNo)} 吗？`,
        success: (res) => {
          if (res.confirm) {
            this.unbindCard(card);
          }
        }
      });
    },
    async unbindCard(card) {
      if (!card.protocolNo) {
        uni.showToast({ title: '缺少协议号，无法解绑', icon: 'none' });
        return;
      }
      
      uni.showLoading({ title: '解绑中...' });
      try {
        const res = await unSignCard({ protocolNo: card.protocolNo });
        uni.hideLoading();
        
        if (res.code === 200) {
          uni.showToast({ title: '解绑成功', icon: 'success' });
          // 重新获取卡列表
          setTimeout(() => {
            this.getCardList();
          }, 1000);
        } else {
          uni.showToast({ title: res.msg || '解绑失败', icon: 'none' });
        }
      } catch (e) {
        uni.hideLoading();
        uni.showToast({ title: '解绑失败', icon: 'none' });
      }
    }
  },
  mounted() {
    const userId = this.$store && this.$store.state && this.$store.state.user && this.$store.state.user.userId;
    if (userId) {
      this.form.userId = userId;
    }
    this.getCardList()
  }
}
</script>

<style scoped>
.bind-card-container {
  min-height: 100vh;
  background: #f5f6f7;
  padding: 24rpx;
}
.section-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 18rpx;
}
/* 微信风格银行卡列表 */
.wx-card-item {
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(60,150,243,0.08);
  padding: 32rpx 28rpx 20rpx 28rpx;
  margin-bottom: 28rpx;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}
.wx-card-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.wx-card-no {
  font-size: 36rpx;
  color: #222;
  font-weight: bold;
  letter-spacing: 4rpx;
}
.wx-card-actions {
  display: flex;
  align-items: center;
  gap: 10rpx;
}
.wx-unbind-btn {
  font-size: 24rpx;
  color: #f56c6c;
  border: 1px solid #f56c6c;
  border-radius: 30rpx;
  padding: 6rpx 16rpx;
  line-height: 1.2;
  background: #fff;
  margin-right: 10rpx;
  min-width: auto;
  height: auto;
}
.wx-unbind-btn::after {
  border: none;
}
.wx-card-info-row {
  display: flex;
  align-items: center;
  gap: 24rpx;
  margin-top: 8rpx;
}
.wx-card-bank {
  font-size: 26rpx;
  color: #888;
}
.wx-card-owner {
  font-size: 24rpx;
  color: #bbb;
}
.wx-empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 60rpx 0 40rpx 0;
}
.wx-empty-img {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 18rpx;
  opacity: 0.7;
}
.wx-empty-text {
  color: #bbb;
  font-size: 28rpx;
}
.bind-btn-section {
  margin-top: 40rpx;
  text-align: center;
}
.wx-bind-popup-bg {
  background: #f5f6f7;
  border-radius: 32rpx;
  padding: 0;
}
.wx-bind-popup {
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx 32rpx 32rpx 32rpx;
  width: 92vw;
  max-width: 700rpx;
  box-sizing: border-box;
  box-shadow: 0 8rpx 32rpx rgba(60,150,243,0.08);
}
.wx-popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin-bottom: 36rpx;
}
.wx-form-list {
  width: 100%;
}
.wx-form-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  padding: 0 0 0 0;
  height: 88rpx;
  margin-bottom: 0;
}
.wx-label {
  width: 180rpx;
  font-size: 30rpx;
  color: #333;
  flex-shrink: 0;
}
.wx-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 30rpx;
  color: #222;
  background: transparent;
  padding: 0 0 0 0;
  height: 88rpx;
}
.picker-value {
  font-size: 30rpx;
  color: #222;
  padding: 0 0 0 0;
  height: 88rpx;
  display: flex;
  align-items: center;
}
.wx-btn-section {
  margin-top: 48rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}
.wx-btn {
  width: 100%;
  height: 88rpx;
  font-size: 32rpx;
  border-radius: 44rpx;
  background: #07c160;
  color: #fff;
  margin-bottom: 0;
  border: none;
}
.wx-btn-cancel {
  width: 100%;
  height: 88rpx;
  font-size: 32rpx;
  border-radius: 44rpx;
  background: #e8f5e9;
  color: #07c160;
  border: 1px solid #07c160;
}
.wx-sms-section {
  margin-top: 36rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}
.wx-qrcode-label {
  font-size: 28rpx;
  color: #888;
  margin-bottom: 8rpx;
  text-align: left;
}
.wx-sms-code-box {
  margin: 32rpx 0 24rpx 0;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}
.wx-sms-code-cells {
  display: flex;
  gap: 16rpx;
}
.wx-sms-code-cell {
  width: 64rpx;
  height: 64rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  font-size: 36rpx;
  color: #222;
  text-align: center;
  line-height: 64rpx;
  background: #f7f7f7;
  transition: border-color 0.2s;
}
.wx-sms-code-cell.active {
  border-color: #07c160;
}
.wx-required {
  color: #f56c6c;
  margin-left: 4rpx;
  font-size: 26rpx;
}
</style> 